﻿/*----------------------------------------------------------------
// Copyright (C) 梦幻天堂
// 版权所有。 
//
// 文件名：DBOperation.cs
// 文件功能描述：数据库操作类
// DBOperation：创建连接字符串，打开、关闭、释放连接，执行存储过程
// DataBase：执行存储过程或SQL语句
//
// 
// 创建标识：田银
// 创建时间：2011/11/7
//
//修改标识：
//修改描述：
//
//----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
using System.Collections;
using System.Xml;
using System.Net;

namespace LYM.CommonWeb.DataServer
{
    public class SQLTools
    {
        List<SqlParameter> lstPara = null;
        public SQLTools()
        {
            lstPara = new List<SqlParameter>();
        }

        /// <summary>
        /// 创建SqlParameter对象
        /// </summary>
        /// <param name="name">名称</param>
        /// <param name="type">类型</param>
        /// <param name="value">参数值</param>
        /// <returns>SqlParameter对象</returns>
        private static SqlParameter CreateSqlParameter(string name, SqlDbType type, object value)
        {
            if (value == null)
            {
                value = DBNull.Value;
            }
            if (!name.StartsWith("@"))
            {
                name = "@" + name;
            }
            SqlParameter sp = new SqlParameter(name, type);
            sp.Value = value;
            return sp;
        }
        /// <summary>
        /// 创建参数
        /// </summary>
        /// <param name="name"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private static SqlParameter CreateSqlParameter(string name, SqlDbType type)
        {
            if (!name.StartsWith("@"))
            {
                name = "@" + name;
            }
            SqlParameter sp = new SqlParameter(name, type);
            return sp;
        }

        /// <summary>
        /// 创建SqlParameter对象
        /// </summary>
        /// <param name="name">名称</param>
        /// <param name="type">类型</param>
        /// <param name="direction">参数值</param>
        /// <returns>SqlParameter对象</returns>
        private static SqlParameter CreateSqlParameter(string name, SqlDbType type, ParameterDirection direction)
        {
            if (!name.StartsWith("@"))
            {
                name = "@" + name;
            }
            SqlParameter sp = new SqlParameter(name, type);
            sp.Direction = direction;
            return sp;
        }

        /// <summary>
        /// 创建SqlParameter对象
        /// </summary>
        /// <param name="name">名称</param>
        /// <param name="type">类型</param>
        /// <param name="size">参数值</param>
        /// <param name="value">SqlParameter对象</param>
        /// <returns>SqlParameter对象</returns>
        private static SqlParameter CreateSqlParameter(string name, SqlDbType type, int size, object value)
        {
            if (value == null)
            {
                value = DBNull.Value;
            }
            if (!name.StartsWith("@"))
            {
                name = "@" + name;
            }
            SqlParameter sp = new SqlParameter(name, type, size);
            sp.Value = value;
            return sp;
        }

        /// <summary>
        /// 创建SqlParameter对象
        /// </summary>
        /// <param name="name">名称</param>
        /// <param name="type">类型</param>
        /// <param name="size">参数值</param>
        /// <param name="value">SqlParameter对象</param>
        /// <param name="direction">方向</param>
        /// <returns>SqlParameter对象</returns>
        private static SqlParameter CreateSqlParameter(string name, SqlDbType type, int size, object value, ParameterDirection direction)
        {
            if (value == null)
            {
                value = DBNull.Value;
            }
            if (!name.StartsWith("@"))
            {
                name = "@" + name;
            }
            SqlParameter sp = new SqlParameter(name, type, size);
            sp.Direction = direction;
            sp.Value = value;
            return sp;
        }

        /// <summary>
        /// 添加SqlParameter对象
        /// </summary>
        /// <param name="name">名称</param>
        /// <param name="type">类型</param>
        /// <param name="value">值</param>
        public void AddSqlParameter(string name, SqlDbType type, object value)
        {
            lstPara.Add(CreateSqlParameter(name, type, value));
        }

        /// <summary>
        /// 添加SqlParameter对象
        /// </summary>
        /// <param name="name">名称</param>
        /// <param name="type">类型</param>
        /// <param name="size">大小</param>
        /// <param name="value">值</param>
        public void AddSqlParameter(string name, SqlDbType type, int size, object value)
        {
            lstPara.Add(CreateSqlParameter(name, type, size, value));
        }

        /// <summary>
        /// 添加SqlParameter对象
        /// </summary>
        /// <param name="name">名称</param>
        /// <param name="type">类型</param>
        /// <param name="size">大小</param>
        /// <param name="value">值</param>
        /// <param name="direction">方向</param>
        public void AddSqlParameter(string name, SqlDbType type, int size, object value, ParameterDirection direction)
        {
            lstPara.Add(CreateSqlParameter(name, type, size, value, direction));
        }

        /// <summary>
        /// 添加SqlParameter对象
        /// </summary>
        /// <param name="name">名称</param>
        /// <param name="type">类型</param>
        public void AddSqlParameter(string name, SqlDbType type)
        {
            lstPara.Add(CreateSqlParameter(name, type));
        }

        /// <summary>
        /// 添加SqlParameter对象
        /// </summary>
        /// <param name="name">名称</param>
        /// <param name="type">类型</param>
        /// <param name="direction">方向</param>
        public void AddSqlParameter(string name, SqlDbType type, ParameterDirection direction)
        {
            lstPara.Add(CreateSqlParameter(name, type, direction));
        }

        /// <summary>
        /// 得到SqlParameter数组
        /// </summary>
        /// <returns>SqlParameter数组</returns>
        public SqlParameter[] GetSqlParameters()
        {
            return lstPara.ToArray();
        }
        /// <summary>
        /// 根据参数名获取参数
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public SqlParameter GetSqlParameterByName(string name)
        {
            if (!name.StartsWith("@"))
            {
                name = "@" + name;
            }
            foreach (SqlParameter sp in lstPara)
            {
                if (sp.ParameterName == name)
                {
                    return sp;
                }
            }
            return null;
        }
    }

    /// <summary>
    /// 类名：DBOperation
    /// 作用：创建连接字符串，打开、关闭、释放连接，执行存储过程
    /// </summary>
    public sealed class DBOperation
    {
        private SqlConnection con;
        private readonly string RETURNVALUE = "RETURNVALUE";
        //记录错误日志位置
        private static string m_fileName = "c:\\Systemlog.txt";
        public DBOperation()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }
        #region 创建连接字符串
        /// <summary>
        /// CreateCon创建连接字符串
        /// </summary>
        /// <returns></returns>
        public SqlConnection CreateCon()
        {
            SqlConnection con = new SqlConnection("server=61.129.47.15;database=taobao; uid=taobao;pwd=870104");
            //或者使用如下方式，调用webConfig的连接字符串
            //string strcon = ConfigurationManager.ConnectionStrings["yhqhjnConnectionString"].ConnectionString;
            //SqlConnection con = new SqlConnection(strcon);
            return con;
        }

        #endregion

        #region 打开数据库连接.
        private void Open()
        {
            // 打开数据库连接
            if (con == null)
            {
                con = CreateCon();
            }

            if (con.State == ConnectionState.Closed)
            {
                try
                {
                    ///打开数据库连接
                    con.Open();
                }
                catch (Exception ex)
                {
                    DBOperation.CreateErrorMsg(ex.Message);
                }
                finally
                {
                    ///关闭已经打开的数据库连接				
                }
            }
        }
        #endregion

        #region 关闭数据库连接
        public void Close()
        {
            ///判断连接是否已经创建
            if (con != null)
            {
                ///判断连接的状态是否打开
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
            }
        }
        #endregion

        #region 释放资源
        public void Dispose()
        {
            // 确认连接是否已经关闭
            if (con != null)
            {
                con.Dispose();
                con = null;
            }
        }
        #endregion

        #region 执行无参存储过程
        /// <summary>
        /// 执行存储过程,执行添加、删除、更新类型操作
        /// </summary>
        public int RunProc(string procName)
        {
            SqlCommand cmd = CreateProcCommand(procName, null);
            ///执行存储过程
            cmd.ExecuteNonQuery();
            ///关闭数据库的连接
            Close();

            ///返回存储过程的参数值
            return (int)cmd.Parameters[RETURNVALUE].Value;
        }
        #endregion

        #region 执行有参存储过程
        /// <summary>
        /// 执行存储过程，执行添加、删除、更新类型操作
        /// </summary>
        /// <param name="procName">存储过程名</param>
        /// <param name="prams">参数列表</param>
        /// <returns></returns>
        public int RunProc(string procName, SqlParameter[] prams)
        {
            SqlCommand cmd = CreateProcCommand(procName, prams);
            ///执行存储过程
            cmd.ExecuteNonQuery();
            ///关闭数据库的连接
            Close();

            ///返回存储过程的参数值
            return (int)cmd.Parameters[RETURNVALUE].Value;
        }
        #endregion

        #region 执行无参存储过程，返回datareader对象
        /// <summary>
        /// 执行存储过程，执行选择类型操作
        /// </summary>
        /// <param name="procName">存储过程名</param>
        /// <param name="dataReader">要返回的DataReader对象</param>
        public void RunProc(string procName, out SqlDataReader dataReader)
        {
            ///创建Command
            SqlCommand cmd = CreateProcCommand(procName, null);

            ///读取数据
            dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
        }

        #endregion

        #region 执行有参存储过程，返回datareader对象
        /// <summary>
        /// 执行存储过程，执行选择类型操作
        /// </summary>
        public void RunProc(string procName, SqlParameter[] prams, out SqlDataReader dataReader)
        {
            ///创建Command
            SqlCommand cmd = CreateProcCommand(procName, prams);

            ///读取数据
            dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
        }
        #endregion

        #region 执行无参存储过程，返回DataSet对象
        /// <summary>
        /// 执行无参存储过程，返回DataSet对象
        /// </summary>
        /// <param name="procName">存储过程名</param>
        /// <param name="dataSet"></param>
        public void RunProc(string procName, ref DataSet dataSet)
        {
            if (dataSet == null)
            {
                dataSet = new DataSet();
            }
            ///创建SqlDataAdapter
            SqlDataAdapter da = CreateProcDataAdapter(procName, null);

            ///读取数据
            da.Fill(dataSet);
            ///关闭数据库的连接
            Close();
        }

        #endregion

        #region 执行有参存储过程，返回DataSet对象
        /// <summary>
        /// 执行有参存储过程，返回DataSet对象
        /// </summary>
        /// <param name="procName">存储过程名</param>
        /// <param name="prams">参数列表</param>
        /// <param name="dataSet">返回对象</param>
        public void RunProc(string procName, SqlParameter[] prams, ref DataSet dataSet)
        {
            if (dataSet == null)
            {
                dataSet = new DataSet();
            }
            ///创建SqlDataAdapter
            SqlDataAdapter da = CreateProcDataAdapter(procName, prams);

            ///读取数据
            da.Fill(dataSet);
            ///关闭数据库的连接
            Close();
        }
        #endregion


        #region 创建一个SqlCommand对象以此来执行存储过程
        /// <summary>
        /// 创建一个SqlCommand对象以此来执行存储过程
        /// </summary>
        /// <param name="procName">存储过程名</param>
        /// <param name="prams">存储过程参数</param>
        /// <returns></returns>

        private SqlCommand CreateProcCommand(string procName, SqlParameter[] prams)
        {
            Open();
            ///设置Command
            SqlCommand cmd = new SqlCommand(procName, con);
            cmd.CommandType = CommandType.StoredProcedure;

            ///添加把存储过程的参数
            if (prams != null)
            {
                foreach (SqlParameter parameter in prams)
                {
                    cmd.Parameters.Add(parameter);
                }
            }

            ///添加返回参数ReturnValue
            cmd.Parameters.Add(
                new SqlParameter(RETURNVALUE, SqlDbType.Int, 4, ParameterDirection.ReturnValue,
                false, 0, 0, string.Empty, DataRowVersion.Default, null));

            ///返回创建的SqlCommand对象
            return cmd;
        }

        #endregion

        #region 创建一个SqlDataAdapter对象，用此来执行存储过程
        /// <summary>
        /// 创建一个SqlDataAdapter对象，用此来执行存储过程
        /// </summary>
        /// <param name="procName">存储过程名</param>
        /// <param name="prams">参数列表</param>
        /// <returns></returns>
        private SqlDataAdapter CreateProcDataAdapter(string procName, SqlParameter[] prams)
        {
            ///打开数据库连接
            Open();

            ///设置SqlDataAdapter对象
            SqlDataAdapter da = new SqlDataAdapter(procName, con);
            da.SelectCommand.CommandType = CommandType.StoredProcedure;

            ///添加把存储过程的参数
            if (prams != null)
            {
                foreach (SqlParameter parameter in prams)
                {
                    da.SelectCommand.Parameters.Add(parameter);
                }
            }

            ///添加返回参数ReturnValue
            da.SelectCommand.Parameters.Add(
                new SqlParameter(RETURNVALUE, SqlDbType.Int, 4, ParameterDirection.ReturnValue,
                false, 0, 0, string.Empty, DataRowVersion.Default, null));

            ///返回创建的SqlDataAdapter对象
            return da;
        }
        #endregion

        #region 生成存储过程参数
        /// <summary>
        /// 生成存储过程参数
        /// </summary>
        /// <param name="ParamName">参数名称</param>
        /// <param name="DbType">参数类型</param>
        /// <param name="Size">参数大小</param>
        /// <param name="Direction">形式参数类型</param>
        /// <param name="Value">形参名称</param>
        /// <returns></returns>
        public SqlParameter CreateParam(string ParamName, SqlDbType DbType, Int32 Size, ParameterDirection Direction, object Value)
        {
            SqlParameter param = null;

            ///当参数大小为0时，不使用该参数大小值
            if (Size > 0)
            {
                param = new SqlParameter(ParamName, DbType, Size);
            }
            else
            {
                ///当参数大小为0时，不使用该参数大小值
                param = new SqlParameter(ParamName, DbType);
            }

            ///创建输出类型的参数
            param.Direction = Direction;
            if (!(Direction == ParameterDirection.Output && Value == null))
            {
                param.Value = Value;
            }
            ///返回创建的参数
            return param;
        }
        #endregion

        #region 输入传入参数
        /// <summary>
        /// 输入传入参数和
        /// </summary>
        /// <param name="ParamName">参数名称</param>
        /// <param name="DbType">参数类型</param>
        /// <param name="Size">参数大小</param>
        /// <param name="Value">参数值</param>
        /// <returns></returns>
        public SqlParameter CreateInParam(string ParamName, SqlDbType DbType, int Size, object Value)
        {
            return CreateParam(ParamName, DbType, Size, ParameterDirection.Input, Value);
        }
        #endregion

        #region 传入返回值参数
        /// <summary>
        /// 传入返回值参数
        /// </summary>
        public SqlParameter CreateOutParam(string ParamName, SqlDbType DbType, int Size)
        {
            return CreateParam(ParamName, DbType, Size, ParameterDirection.Output, null);
        }
        #endregion

        #region 传入返回值参数
        /// <summary>
        /// 传入返回值参数
        /// </summary>
        public SqlParameter CreateReturnParam(string ParamName, SqlDbType DbType, int Size)
        {
            return CreateParam(ParamName, DbType, Size, ParameterDirection.ReturnValue, null);
        }
        #endregion

        #region 将DataReader转为DataTable
        /// <summary>
        /// 将DataReader转为DataTable
        /// </summary>
        /// <param name="dataReader"></param>
        /// <returns></returns>
        public static DataTable ConvertdrTodt(SqlDataReader dataReader)
        {
            ///定义DataTable
            DataTable datatable = new DataTable();

            ///动态添加表的数据列
            for (int i = 0; i < dataReader.FieldCount; i++)
            {
                DataColumn mydc = new DataColumn();
                mydc.DataType = dataReader.GetFieldType(i);
                mydc.ColumnName = dataReader.GetName(i);
                datatable.Columns.Add(mydc);
            }

            ///添加表的数据
            while (dataReader.Read())
            {
                DataRow mydr = datatable.NewRow();
                for (int i = 0; i < dataReader.FieldCount; i++)
                {
                    mydr[i] = dataReader[i].ToString();
                }
                datatable.Rows.Add(mydr);
                mydr = null;
            }
            ///关闭数据读取器
            dataReader.Close();
            return datatable;
        }

        #endregion

        #region 记录日志至文本文件
        /// <summary>
        /// 记录日志至文本文件
        /// </summary>
        /// <param name="message">记录的内容</param>
        public static void CreateErrorMsg(string message)
        {
            if (File.Exists(m_fileName))
            {
                ///如果日志文件已经存在，则直接写入日志文件
                StreamWriter sr = File.AppendText(m_fileName);
                sr.WriteLine("\n");
                sr.WriteLine(DateTime.Now.ToString() + message);
                sr.Close();
            }
            else
            {
                ///创建日志文件
                StreamWriter sr = File.CreateText(m_fileName);
                sr.Close();
            }
        }
        #endregion

    }

    /// <summary>
    /// 类名：DataBase
    /// 作用：执行存储过程或SQL语句
    /// </summary>
    public sealed class DataBase
    {
        /// <summary>
        /// 初始化连接字符串
        /// </summary>
        /// <param name="conStr">连接字符串</param>
        /// <param name="isSaveLog">是否需要保存错误日志</param>
        public DataBase(string conStr, bool isSaveLog)
        {
            bz = isSaveLog;
            con = new SqlConnection(conStr);
        }

        /// <summary>
        /// 初始化连接字符串和系统日志保存路径
        /// </summary>
        /// <param name="conStr">连接字符串</param>
        /// <param name="log">系统日志保存路径</param>
        /// <param name="isSaveLog">是否需要保存错误日志</param>
        public DataBase(string conStr, string log, bool isSaveLog)
        {
            logPath = log;
            bz = isSaveLog;
            con = new SqlConnection(conStr);
        }

        static bool bz = true;
        //记录错误日志位置
        static string logPath = "c:\\Systemlog.txt";

        //static string str = "Data Source=10.12.17.32;Initial Catalog=issuetracker;uid=sa;pwd=hisoft;";
        //创建连接字符串对象

        SqlConnection con = null;
        //创建命令对象
        SqlCommand cmd = null;
        //创建连接对象
        SqlDataAdapter da = null;
        //DataSet ds = null;
        ////创建一个表对象
        //DataTable dt = null;
        //SqlParameter[] values = null;
        //string sql = null;

        #region 具体数据查询的方法

        /// <summary>
        /// 调用方法查询一个或多个表的信息，并返回DataSet类型值的方法
        /// </summary>
        /// <remarks>
        /// e.g.:  
        /// DataSet ds = new DataSet();
        /// this.GetDataSet("SQL",false,ref ds, new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="sql">sql语句或存储过程名</param>
        /// <param name="re">是否是存储过程</param>
        /// <param name="values">参数</param>
        /// <returns>返回DataSet</returns>
        public void GetDataSet(string sql, bool re, ref DataSet ds, params SqlParameter[] values)
        {
            da = new SqlDataAdapter(sql, con);

            if (re)
            {
                //定义命令类型
                da.SelectCommand.CommandType = CommandType.StoredProcedure;
            }//if (re)//判断命令类型

            if (values != null)
            {
                //添加参数
                da.SelectCommand.Parameters.AddRange(values);
            }//if (values != null)//判断参数是否存在

            try
            {
                da.Fill(ds);

            }//try
            catch (SqlException ex)
            {
                //写错误日志
                if (bz)
                    CreateErrorMsg(ex.Message);
            }//try catch(SqlException ex)捕获数据库异常
            finally
            {

                if (con.State == ConnectionState.Open)
                {
                    //关闭连接
                    con.Close();
                }//if (con.State == ConnectionState.Open)关闭连接

            }//try catch(SqlException ex) finally

        }//public DataSet GetDataSet(string sql, bool re, params SqlParameter[] values)

        /// <summary>
        /// 调用方法查询单个表的信息，并返回DataTable类型值的方法
        /// </summary>
        /// <remarks>
        /// e.g.:  
        /// DataTable dt = new DataTable();
        /// this.GetDataTable("SQL",false,ref dt, new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="sql">sql语句或存储过程名</param>
        /// <param name="re">是否是存储过程</param>
        /// <param name="values">参数</param>
        /// <returns>返回DataTable</returns>
        public void GetDataTable(string sql, bool re, ref DataTable dt, params SqlParameter[] values)
        {
            da = new SqlDataAdapter(sql, con);

            if (re)
            {
                //定义命令类型
                da.SelectCommand.CommandType = CommandType.StoredProcedure;
            }//if (re)

            if (values != null)
            {
                //添加参数
                da.SelectCommand.Parameters.AddRange(values);
            }//if (values != null)

            try
            {
                da.Fill(dt);
            }//try
            catch (SqlException ex)
            {
                //写错误日志
                if (bz)
                    CreateErrorMsg(ex.Message);
            }//try catch(SqlException ex)
            finally
            {

                if (con.State == ConnectionState.Open)
                {
                    //关闭连接
                    con.Close();
                }//if (con.State == ConnectionState.Open)

            }//try catch(SqlException ex) finally

        }//public DataTable GetDataTable(string sql, bool re, params SqlParameter[] values)

        /// <summary>
        /// 调用方法查询单个值，返回object类型值的方法
        /// </summary>
        /// <remarks>
        /// e.g.:  
        /// object strReturn=null;
        /// this.GetValue("SQL",false,ref strReturn, new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="sql">sql语句或存储过程名</param>
        /// <param name="re">是否是存储过程</param>
        /// <param name="values">参数</param>
        /// <returns>返回object</returns>
        public void GetValue(string sql, bool re, ref object strReturn, params SqlParameter[] values)
        {
            try
            {
                cmd = new SqlCommand(sql, con);
                if (re)
                {
                    //定义命令类型
                    cmd.CommandType = CommandType.StoredProcedure;
                }//if (re)

                if (values != null)
                {
                    //添加参数
                    cmd.Parameters.AddRange(values);
                }//if (values != null)


                if (con.State == ConnectionState.Closed)
                {
                    //打开连接
                    con.Open();
                }//if(con.State == ConnectionState.Closed)
                //读取一行一列的数据
                strReturn = cmd.ExecuteScalar();
                //如果返回值是数据库空值类型
                if (strReturn == DBNull.Value)
                {
                    strReturn = null;
                }
            }//try
            catch (SqlException ex)
            {
                //写错误日志
                if (bz)
                    CreateErrorMsg(ex.Message);
            }//try catch(SqlException ex)
            finally
            {

                if (con.State == ConnectionState.Open)
                {
                    //关闭连接
                    con.Close();
                }//if (con.State == ConnectionState.Open)

            }//try catch(SqlException ex) finally

        }//public object GetValue(string sql, bool re, params SqlParameter[] values)

        /// <summary>
        /// 调用方法更新数据库，并返回受影响行数
        /// </summary>
        /// <remarks>
        /// e.g.:  
        /// int count=0;
        /// this.ProExecuteCommand("SQL",false,ref count, new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="sql">sql语句或存储过程名</param>
        /// <param name="re">是否是存储过程</param>
        /// <param name="values">参数</param>
        /// <returns>返回受影响行数</returns>
        public void ProExecuteCommand(string sql, bool re, ref int count, params SqlParameter[] values)
        {
            cmd = new SqlCommand(sql, con);

            if (re)
            {
                //定义命令类型
                cmd.CommandType = CommandType.StoredProcedure;
            }//if(re)

            if (values != null)
            {
                //向命令对象的参数集合里添加参数
                cmd.Parameters.AddRange(values);
            }//if(values != null)

            try
            {

                if (con.State == ConnectionState.Closed)
                {
                    //打开连接
                    con.Open();
                }//if(con.State == ConnectionState.Closed)

                count = cmd.ExecuteNonQuery();//  执行命令，返回受影响行数
            }//try
            catch (SqlException ex)
            {
                //写错误日志
                if (bz)
                    CreateErrorMsg(ex.Message);
            }//try catch(SqlException ex)
            finally
            {

                if (con.State == ConnectionState.Open)
                {
                    //关闭连接
                    con.Close();
                }//if (con.State == ConnectionState.Open)

            }//try catch(SqlException ex) finally

        }//public int ProExecuteCommand(string sql, bool re, params SqlParameter[] values)

        #endregion

        #region 记录日志至文本文件
        /// <summary>
        /// 记录日志至文本文件
        /// </summary>
        /// <param name="message">记录的内容</param>
        public void CreateErrorMsg(string message)
        {
            if (File.Exists(logPath))
            {
                ///如果日志文件已经存在，则直接写入日志文件
                StreamWriter sr = File.AppendText(logPath);
                sr.WriteLine("\n");
                sr.WriteLine(DateTime.Now.ToString() + message);
                sr.Close();
            }
            else
            {
                ///创建日志文件
                StreamWriter sr = File.CreateText(logPath);
                sr.Close();
            }
        }
        #endregion
    }


    /// <summary>
    /// The SqlHelper class is intended to encapsulate high performance, 
    /// scalable best practices for common uses of SqlClient.
    /// </summary>
    public abstract class SqlHelper
    {

        // Hashtable to store cached parameters
        private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());

        /// <summary>
        /// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>an int representing the number of rows affected by the command</returns>
        public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {

            SqlCommand cmd = new SqlCommand();

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                int val = cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
                return val;
            }
        }

        /// <summary>
        /// Execute a SqlCommand (that returns no resultset) against an existing database connection 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="conn">an existing database connection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>an int representing the number of rows affected by the command</returns>
        public static int ExecuteNonQuery(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {

            SqlCommand cmd = new SqlCommand();

            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }

        /// <summary>
        /// Execute a SqlCommand (that returns no resultset) using an existing SQL Transaction 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="trans">an existing sql transaction</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>an int representing the number of rows affected by the command</returns>
        public static int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }

        /// <summary>
        /// Execute a SqlCommand that returns a resultset against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>A SqlDataReader containing the results</returns>
        public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            SqlConnection conn = new SqlConnection(connectionString);

            // we use a try/catch here because if the method throws an exception we want to 
            // close the connection throw code, because no datareader will exist, hence the 
            // commandBehaviour.CloseConnection will not work
            try
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return rdr;
            }
            catch
            {
                conn.Close();
                throw;
            }
        }

        public static DataTable ExecuteGetTable(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandTimeout = 120;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                cmd.Parameters.Clear();
                return dt;
            }
        }


        public static DataSet ExecuteGetDataSet(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandTimeout = 120;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                cmd.Parameters.Clear();
                return ds;
            }
        }


        /// <summary>
        /// Execute a SqlCommand that returns the first column of the first record against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
        public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
                object val = cmd.ExecuteScalar();
                cmd.Parameters.Clear();
                return val;
            }
        }

        /// <summary>
        /// Execute a SqlCommand that returns the first column of the first record against an existing database connection 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="conn">an existing database connection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
        public static object ExecuteScalar(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {

            SqlCommand cmd = new SqlCommand();

            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
            object val = cmd.ExecuteScalar();
            cmd.Parameters.Clear();
            return val;
        }

        /// <summary>
        /// add parameter array to the cache
        /// </summary>
        /// <param name="cacheKey">Key to the parameter cache</param>
        /// <param name="cmdParms">an array of SqlParamters to be cached</param>
        public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters)
        {
            parmCache[cacheKey] = commandParameters;
        }

        /// <summary>
        /// Retrieve cached parameters
        /// </summary>
        /// <param name="cacheKey">key used to lookup parameters</param>
        /// <returns>Cached SqlParamters array</returns>
        public static SqlParameter[] GetCachedParameters(string cacheKey)
        {
            SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey];

            if (cachedParms == null)
                return null;

            SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length];

            for (int i = 0, j = cachedParms.Length; i < j; i++)
                clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone();

            return clonedParms;
        }

        /// <summary>
        /// Prepare a command for execution
        /// </summary>
        /// <param name="cmd">SqlCommand object</param>
        /// <param name="conn">SqlConnection object</param>
        /// <param name="trans">SqlTransaction object</param>
        /// <param name="cmdType">Cmd type e.g. stored procedure or text</param>
        /// <param name="cmdText">Command text, e.g. Select * from Products</param>
        /// <param name="cmdParms">SqlParameters to use in the command</param>
        private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
        {

            if (conn.State != ConnectionState.Open)
                conn.Open();

            cmd.Connection = conn;
            cmd.CommandText = cmdText;

            if (trans != null)
                cmd.Transaction = trans;

            cmd.CommandType = cmdType;

            if (cmdParms != null)
            {
                foreach (SqlParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
            }
        }

        public static List<T> DataConvert<T>(DataTable tb)
        {
            List<T> lst = new List<T>();
            DataConvert<T>(tb, ref lst);
            return lst;
        }

        public static List<T> DataConvert<T>(DataTable tb, ref List<T> lst)
        {
            for (int i = 0; i < tb.Rows.Count; i++)
            {
                lst.Add(DataConvert<T>(tb.Rows[i]));
            }
            return lst;
        }

        public static T DataConvert<T>(DataRow row, ref T t)
        {
            var ps = t.GetType().GetProperties();
            var tbColumns = row.Table.Columns;
            foreach (var c in ps)
            {
                var colName = c.Name;
                if (tbColumns.Contains(colName))
                {
                    object nr = row[colName] == DBNull.Value ? null : row[colName];
                    if (nr == null)
                    {
                        c.SetValue(t, nr, null);
                    }
                    else
                    {
                        var nrType = c.PropertyType;
                        if (nrType == typeof(decimal) || nrType == typeof(decimal?))
                        {
                            nr = Convert.ToDecimal(nr);
                        }
                        else if (nrType == typeof(Int64) || nrType == typeof(Int64?))
                        {
                            nr = Convert.ToInt64(nr);
                        }
                        else if (nrType == typeof(double) || nrType == typeof(double?))
                        {
                            nr = Convert.ToDouble(nr);
                        }
                        else if (nrType == typeof(Int32) || nrType == typeof(Int32?))
                        {
                            nr = Convert.ToInt32(nr);
                        }
                        else if (nrType == typeof(Int16) || nrType == typeof(Int16?))
                        {
                            nr = Convert.ToInt16(nr);
                        }
                        c.SetValue(t, nr, null);
                    }

                }
            }
            return t;
        }

        public static T DataConvert<T>(DataRow row)
        {
            var type = typeof(T);
            object obj = type.Assembly.CreateInstance(type.FullName);
            var c = (T)obj;
            DataConvert(row, ref c);
            return c;
        }

        /// <summary>
        /// 根据某个条件得到某列的数据
        /// </summ
        /// ary>
        /// <param name="conn">数据库连接字符串</param>
        /// <param name="columns">表的列的数组</param>
        /// <param name="tableName">表名</param>
        /// <param name="where">查询条件</param>
        /// <returns></returns>
        public static DataTable GetDataByColumns(string conn, string[] columns, string tableName, string where)
        {
            if (columns == null || columns.Length == 0)
            {
                throw new Exception("columns不能为空或者元素个数为0");
            }
            string cols = " ";
            foreach (var c in columns)
            {
                if (c == "*")
                {
                    cols += c + ",";
                }
                else
                {
                    cols += "[" + c + "],";
                }
            }
            cols = cols.Substring(0, cols.Length - 1);
            string sql = "select" + cols + " from " + tableName + " where " + where;
            return SqlHelper.ExecuteGetTable(conn, CommandType.Text, sql, null);
        }

        /// <summary>
        /// 根据某个条件得到某列的数据
        /// </summary>
        /// <param name="conn">数据库连接字符串</param>
        /// <param name="columns">表的列</param>
        /// <param name="tableName">表名</param>
        /// <param name="where">查询条件</param>
        /// <returns></returns>
        public static DataTable GetDataByColumns(string conn, string column, string tableName, string where)
        {
            if (string.IsNullOrEmpty(column))
            {
                throw new Exception("column字段不能为空");
            }
            string[] columns = new string[] { column };
            return GetDataByColumns(conn, columns, tableName, where);
        }

        public static T GetDataByColumns<T>(string conn, string column, string tableName, string where)
        {
            if (string.IsNullOrEmpty(column))
            {
                throw new Exception("column字段不能为空");
            }
            string[] cols = new string[] { column };

            return GetDataByColumns<T>(conn, cols, tableName, where);
        }

        public static T GetDataByColumns<T>(string conn, string[] columns, string tableName, string where)
        {
            DataTable tb = GetDataByColumns(conn, columns, tableName, where);
            if (tb.Rows.Count > 0)
            {
                return DataConvert<T>(tb.Rows[0]);
            }
            else
            {
                return default(T);
            }
        }

        public static List<T> GetDataByColumnsLst<T>(string conn, string column, string tableName, string where)
        {
            if (string.IsNullOrEmpty(column))
            {
                throw new Exception("column字段不能为空");
            }
            string[] cols = new string[] { column };
            return GetDataByColumnsLst<T>(conn, cols, tableName, where);
        }

        public static List<T> GetDataByColumnsLst<T>(string conn, string[] columns, string tableName, string where)
        {
            DataTable tb = GetDataByColumns(conn, columns, tableName, where);
            return DataConvert<T>(tb);
        }

        public static T GetDataByColumns<T>(string conn, string sql, params SqlParameter[] commandParameters)
        {
            DataTable tb = SqlHelper.ExecuteGetTable(conn, CommandType.Text, sql, commandParameters);
            if (tb.Rows.Count > 0)
            {
                return DataConvert<T>(tb.Rows[0]);
            }
            else
            {
                return default(T);
            }
        }

        public static List<T> GetDataByColumnsLst<T>(string conn, string sql, params SqlParameter[] commandParameters)
        {
            DataTable tb = SqlHelper.ExecuteGetTable(conn, CommandType.Text, sql, commandParameters);
            return DataConvert<T>(tb);
        }

        /// <summary>
        /// 类属性转化成字符串
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string PropertiesToString(Type type, List<string> removeIds, Dictionary<string, string> modifyp)
        {
            Dictionary<string, string> modifyp2 = new Dictionary<string, string>();
            if (modifyp != null)
            {
                foreach (var c in modifyp.Keys)
                {
                    modifyp2.Add(c.ToLower(), modifyp[c]);
                }
            }

            if (removeIds != null)
            {
                for (int i = 0; i < removeIds.Count; i++)
                {
                    removeIds[i] = removeIds[i].ToLower();
                }
            }
            var ps = type.GetProperties();
            StringBuilder sb = new StringBuilder();
            foreach (var c in ps)
            {
                string name = c.Name;
                string lname = name.ToLower();
                if (removeIds == null || !removeIds.Contains(lname))
                {
                    if (modifyp2.ContainsKey(lname))
                    {
                        name = modifyp2[lname];
                        sb.Append(name + ",");
                    }
                    else
                    {
                        sb.Append("[" + name + "],");
                    }

                }
            }
            if (sb.Length > 0)
            {
                sb = sb.Remove(sb.Length - 1, 1);
            }
            return sb.ToString();
        }

        public static SqlParameter[] ObjectToSqlParameters(object obj, string[] removeKey)
        {
            //System.
            List<SqlParameter> lst = new List<SqlParameter>();
            var ps = obj.GetType().GetProperties();
            List<string> lstRemove = new List<string>();
            if (removeKey != null)
            {
                foreach (var c in removeKey)
                {
                    lstRemove.Add(c.ToLower());
                }
            }
            foreach (var c in ps)
            {
                if (lstRemove.Contains(c.Name.ToLower()))
                {
                    continue;
                }
                object value = c.GetValue(obj, null);
                if (c.PropertyType == typeof(int) || c.PropertyType == typeof(int?))
                {
                    lst.Add(CreateSqlParameter(c.Name, SqlDbType.Int, value));
                }
                else if (c.PropertyType == typeof(long) || c.PropertyType == typeof(long?))
                {
                    lst.Add(CreateSqlParameter(c.Name, SqlDbType.BigInt, value));
                }
                else if (c.PropertyType == typeof(string))
                {
                    lst.Add(CreateSqlParameter(c.Name, SqlDbType.VarChar, value));
                }
                else if (c.PropertyType == typeof(bool) || c.PropertyType == typeof(bool?))
                {
                    lst.Add(CreateSqlParameter(c.Name, SqlDbType.Bit, value));
                }
                else if (c.PropertyType == typeof(byte[]))
                {
                    lst.Add(CreateSqlParameter(c.Name, SqlDbType.Binary, value));
                }
                else if (c.PropertyType == typeof(DateTime) || c.PropertyType == typeof(DateTime?))
                {
                    lst.Add(CreateSqlParameter(c.Name, SqlDbType.DateTime, value));
                }
                else if (c.PropertyType == typeof(decimal?) || c.PropertyType == typeof(decimal) || c.PropertyType == typeof(float)
                    || c.PropertyType == typeof(float?) || c.PropertyType == typeof(double) || c.PropertyType == typeof(double?))
                {
                    lst.Add(CreateSqlParameter(c.Name, SqlDbType.Decimal, value));
                }
                else if (c.PropertyType == typeof(System.Guid) || c.PropertyType == typeof(Guid?))
                {
                    lst.Add(CreateSqlParameter(c.Name, SqlDbType.UniqueIdentifier, value));
                }
            }
            return lst.ToArray();
        }

        public static SqlParameter[] ObjectToSqlParameters(object obj)
        {
            return ObjectToSqlParameters(obj, null);
        }

        private static SqlParameter CreateSqlParameter(string name, SqlDbType dbType, object value)
        {
            if (!name.StartsWith("@"))
            {
                name = "@" + name;
            }
            if (value == null)
            {
                value = DBNull.Value;
            }
            SqlParameter sp = new SqlParameter(name, dbType);
            sp.Value = value;
            return sp;
        }
    }

    /// <summary>
    /// SqlHelperParameterCache provides functions to leverage a static cache of procedure parameters, and the
    /// ability to discover parameters for stored procedures at run-time.
    /// </summary>
    public sealed class SqlHelperParameterCache
    {
        //SqlHelperParameterCache 类实现详细信息

        //参数数组缓存在专用 Hashtable 中。从缓存中检索的参数进行内部复制，这样客户端应用程序能够更改参数值以及进行其他操作，而不会影响缓存的参数数组。专用共享函数 CloneParameters 可以实现此目的。


        #region private methods, variables, and constructors

        //Since this class provides only static methods, make the default constructor private to prevent 
        //instances from being created with "new SqlHelperParameterCache()".
        private SqlHelperParameterCache() { }

        private static Hashtable paramCache = Hashtable.Synchronized(new Hashtable());

        /// <summary>
        /// resolve at run time the appropriate set of SqlParameters for a stored procedure
        /// </summary>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="spName">the name of the stored procedure</param>
        /// <param name="includeReturnValueParameter">whether or not to include their return value parameter</param>
        /// <returns></returns>
        private static SqlParameter[] DiscoverSpParameterSet(string connectionString, string spName, bool includeReturnValueParameter)
        {
            using (SqlConnection cn = new SqlConnection(connectionString))
            using (SqlCommand cmd = new SqlCommand(spName, cn))
            {
                cn.Open();
                cmd.CommandType = CommandType.StoredProcedure;

                SqlCommandBuilder.DeriveParameters(cmd);

                if (!includeReturnValueParameter)
                {
                    cmd.Parameters.RemoveAt(0);
                }

                SqlParameter[] discoveredParameters = new SqlParameter[cmd.Parameters.Count]; ;

                cmd.Parameters.CopyTo(discoveredParameters, 0);

                return discoveredParameters;
            }
        }

        //deep copy of cached SqlParameter array
        private static SqlParameter[] CloneParameters(SqlParameter[] originalParameters)
        {
            SqlParameter[] clonedParameters = new SqlParameter[originalParameters.Length];

            for (int i = 0, j = originalParameters.Length; i < j; i++)
            {
                clonedParameters[i] = (SqlParameter)((ICloneable)originalParameters[i]).Clone();
            }

            return clonedParameters;
        }

        #endregion private methods, variables, and constructors

        #region caching functions

        /// <summary>
        /// add parameter array to the cache
        /// </summary>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters to be cached</param>
        public static void CacheParameterSet(string connectionString, string commandText, params SqlParameter[] commandParameters)
        {
            string hashKey = connectionString + ":" + commandText;

            paramCache[hashKey] = commandParameters;
        }

        /// <summary>
        /// retrieve a parameter array from the cache
        /// </summary>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <returns>an array of SqlParamters</returns>
        public static SqlParameter[] GetCachedParameterSet(string connectionString, string commandText)
        {
            string hashKey = connectionString + ":" + commandText;

            SqlParameter[] cachedParameters = (SqlParameter[])paramCache[hashKey];

            if (cachedParameters == null)
            {
                return null;
            }
            else
            {
                return CloneParameters(cachedParameters);
            }
        }

        #endregion caching functions

        #region Parameter Discovery Functions

        /// <summary>
        /// Retrieves the set of SqlParameters appropriate for the stored procedure
        /// </summary>
        /// <remarks>
        /// This method will query the database for this information, and then store it in a cache for future requests.
        /// </remarks>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="spName">the name of the stored procedure</param>
        /// <returns>an array of SqlParameters</returns>
        public static SqlParameter[] GetSpParameterSet(string connectionString, string spName)
        {
            return GetSpParameterSet(connectionString, spName, false);
        }

        /// <summary>
        /// Retrieves the set of SqlParameters appropriate for the stored procedure
        /// </summary>
        /// <remarks>
        /// This method will query the database for this information, and then store it in a cache for future requests.
        /// </remarks>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="spName">the name of the stored procedure</param>
        /// <param name="includeReturnValueParameter">a bool value indicating whether the return value parameter should be included in the results</param>
        /// <returns>an array of SqlParameters</returns>
        public static SqlParameter[] GetSpParameterSet(string connectionString, string spName, bool includeReturnValueParameter)
        {
            string hashKey = connectionString + ":" + spName + (includeReturnValueParameter ? ":include ReturnValue Parameter" : "");

            SqlParameter[] cachedParameters;

            cachedParameters = (SqlParameter[])paramCache[hashKey];

            if (cachedParameters == null)
            {
                cachedParameters = (SqlParameter[])(paramCache[hashKey] = DiscoverSpParameterSet(connectionString, spName, includeReturnValueParameter));
            }

            return CloneParameters(cachedParameters);
        }

        #endregion Parameter Discovery Functions

    }
}
